<script setup lang="ts">
  import { ref, onMounted, nextTick, watch } from 'vue';
  import { useBooleanStore } from '@/store';
  import { Notification } from '@arco-design/web-vue';
  import {
    taskIn,
    sortStoreRoomIn,
    queryPalletCodeMaterial,
    saveUnpackData,
  } from '@/api/sorting-matching';
  import ColumnsList from './columns';

  // 列表头部
  const { columns, columnsTwo } = ColumnsList();

  const booleanStore = useBooleanStore();

  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  // 扫码操作
  const scanCode = ref<string>('');
  const scanInput = ref<any>('');
  // 适当的时间禁用扫码框
  const disabled = ref<boolean>(false);
  // 托盘编码
  const toolCode = ref<string>('');
  // 缓存箱编码
  const workBinCode = ref<string>('');
  // 重复扫缓存箱回库
  const scanHcxOper = ref<boolean>(false);
  // 重复扫工作包回库
  const scanGzbOper = ref<boolean>(false);
  // 重复扫物料回库
  // const scanMaterialOper = ref<boolean>(false);
  // 托盘列表
  const toolTableData = ref<any[]>([]);
  // 缓存箱盘列表
  const workBinTableData = ref<any[]>([]);

  // 分页
  const page = ref<any>({
    currentPage: 1,
    pageSize: 20,
    total: 0,
  });
  // 工作包回库
  async function toolBack() {
    if (toolCode.value === '') {
      Notification.error({
        title: '错误',
        content: '请先扫工作包条码！',
        closable: true,
      });
      return;
    }
    if (scanGzbOper.value) {
      Notification.error({
        title: '错误',
        content: '请不要重复扫托盘回库',
        closable: true,
      });
      return;
    }
    // 调用回库接口
    const data: any = await taskIn({ palletCode: toolCode.value });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
      toolCode.value = '';
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }

  // 缓存箱回库
  async function workBinBack() {
    if (workBinCode.value === '') {
      Notification.error({
        title: '错误',
        content: '请先扫缓存箱条码！',
        closable: true,
      });
      return;
    }
    if (scanHcxOper.value) {
      Notification.error({
        title: '错误',
        content: '请不要重复扫缓存箱回库',
        closable: true,
      });
      return;
    }
    // 调用回库接口
    const data: any = await sortStoreRoomIn({ workbinCode: workBinCode.value });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
      workBinCode.value = '';
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }

  // 查询缓存箱子，托盘列表
  async function queryBarCode() {
    if (scanCode.value.startsWith('11208003')) {
      workBinCode.value = scanCode.value;
      // 调用箱子接口
      const data = await queryPalletCodeMaterial({
        page: page.value,
        searchParams: { palletCode: scanCode.value },
      });
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
        workBinTableData.value = data.responseBody.list;
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
        // workBinTableData.value = [];
      }
    } else if (scanCode.value.startsWith('21208003')) {
      toolCode.value = scanCode.value;
      // 调用托盘接口
      const data = await queryPalletCodeMaterial({
        page: page.value,
        searchParams: { palletCode: scanCode.value },
      });
      if (data.retCode === '200') {
        Notification.success({
          title: '成功',
          content: data.message,
          closable: true,
        });
        toolTableData.value = data.responseBody.list;
      } else {
        Notification.error({
          title: '失败',
          content: data.message,
          closable: true,
        });
        // toolTableData.value = [];
      }
    } else {
      if (workBinCode.value === '') {
        workBinTableData.value = [];
        Notification.error({
          title: '失败',
          content: '请输入缓存箱号',
          closable: true,
        });
        return;
      }
      if (toolCode.value === '') {
        toolTableData.value = [];
        Notification.error({
          title: '失败',
          content: '请输入托盘号',
          closable: true,
        });
        return;
      }
      toolTableData.value = [];
      workBinTableData.value = [];
    }
  }

  // 扫码
  async function scanSubmit() {
    if (scanCode.value === '9004') {
      // 托盘回库
      scanGzbOper.value = false;
      toolBack();
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else if (scanCode.value === '9002') {
      // 缓存箱回库
      scanHcxOper.value = false;
      workBinBack();
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    } else {
      await queryBarCode();
      scanCode.value = '';
      nextTick(() => {
        scanInput.value.focus();
      });
    }
  }

  // 保存按钮
  async function saveEditMaterialInfo() {
    const tools = ref<any[]>([]);
    const isFalse = ref<boolean>(false);
    toolTableData.value.forEach((item: any) => {
      if (item.unpackQty > item.packageCount) {
        isFalse.value = true;
        return;
      }
      if (item.unpackQty > 0) {
        tools.value.push(item);
      }
    });
    if (isFalse.value) {
      Notification.error({
        title: '失败',
        content: '拆包数量不能大于分拣数量',
        closable: true,
      });
      return;
    }
    const data = await saveUnpackData({
      matchinfos: toolTableData.value,
      workbinCode: workBinCode.value,
      toolCode: toolCode.value,
    });
    if (data.retCode === '200') {
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
      queryBarCode();
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }
  // 初始进入页面
  onMounted(() => {
    nextTick(() => {
      scanInput.value.focus();
    });
  });

  // 监听托盘里的物料是否拆包，拆包就要将数据拿到缓存箱里面，为0的时候就要去缓存箱里面清理掉
  watch(
    toolTableData,
    () => {
      toolTableData.value.forEach((item: any) => {
        if (item.unpackQty > 0) {
          // 找到 item 在 workBinTableData.value 中的索引
          const index = workBinTableData.value.findIndex(
            (existingItem: any) => existingItem.itemCode === item.itemCode
          );
          // 如果 unpackQty 大于 0，将 item 添加到 workBinTableData.value
          if (index === -1) {
            workBinTableData.value.push(item);
          }
        } else {
          // 找到 item 在 workBinTableData.value 中的索引
          const index = workBinTableData.value.findIndex(
            (existingItem: any) => existingItem.itemCode === item.itemCode
          ); // 假设每个 item 有唯一的 id

          // 如果找到索引，使用 splice 删除
          if (index !== -1) {
            workBinTableData.value.splice(index, 1);
          }
        }
      });
    },
    { deep: true }
  );
</script>

<template>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">扫码操作</div>
    </template>
    <div>
      <a-row :gutter="8">
        <a-col :span="6">
          <div>
            <a-input
              ref="scanInput"
              v-model="scanCode"
              :disabled="disabled"
              placeholder="请输入缓存箱/托盘码/条码"
              size="large"
              @keyup.enter="scanSubmit()"
            />
          </div>
        </a-col>
        <a-col :span="6">
          <a-button type="primary" @click="saveEditMaterialInfo"
            >执行拆包</a-button
          >
        </a-col>
      </a-row>

      <a-row class="margin-top" :gutter="8">
        <a-col :span="16">
          <div class="flex-column">
            <div class="flex-box">
              <span>托盘：</span>
              <span class="font-size">{{ toolCode }}</span>
            </div>
            <div>
              <a-table
                :stripe="true"
                class="top-table"
                :columns="columns"
                :data="toolTableData"
                :scroll="{ y: 400 }"
                style="height: 250px"
              >
                <template #unpackQty="{ rowIndex }">
                  <a-input v-model="toolTableData[rowIndex].unpackQty" />
                </template>
              </a-table>
            </div>
          </div>
        </a-col>
        <!-- 工作包 -->
        <a-col :span="8">
          <div class="flex-column">
            <div class="flex-box">
              <span>箱号：</span>
              <span class="font-size">{{ workBinCode }}</span>
            </div>
            <div>
              <a-table
                :stripe="true"
                class="top-table"
                :columns="columnsTwo"
                :data="workBinTableData"
                :scroll="{ y: 400 }"
                style="height: 250px"
              >
                <template #index="{ record }">{{
                  workBinTableData.indexOf(record) + 1
                }}</template>
              </a-table>
            </div>
          </div>
        </a-col>
      </a-row>
    </div>
  </a-card>
</template>

<style scoped>
  .margin-top {
    margin-top: 10px;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
  .flex-column {
    display: flex;
    flex-direction: column;
  }

  .font-size {
    font-size: 18px;
    font-weight: bold;
  }

  .flex-box {
    display: flex;
    align-items: center;
    white-space: nowrap;
  }
</style>
